'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import type { Post } from '@/lib'

interface SearchDialogProps {
  onClose: () => void
}

export default function SearchDialog({ onClose }: SearchDialogProps) {
  const [searchTerm, setSearchTerm] = useState('')
  const [results, setResults] = useState<{posts?: Post[]}>()
  const [isLoading, setIsLoading] = useState(false)
  const router = useRouter()

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        onClose()
      }
    }

    document.addEventListener('keydown', handleKeyDown)
    return () => document.removeEventListener('keydown', handleKeyDown)
  }, [onClose])

  useEffect(() => {
    const searchPosts = async () => {
      if (searchTerm.length < 2) {
        setResults({})
        return
      }

      setIsLoading(true)
      try {
        const response = await fetch(`/api/search?q=${encodeURIComponent(searchTerm)}`)
        const data = await response.json()
        console.log(111,data)
        setResults(data)
      } catch (error) {
        console.error('搜索失败:', error)
        setResults({})
      } finally {
        setIsLoading(false)
      }
    }

    const debounceTimer = setTimeout(searchPosts, 300)
    return () => clearTimeout(debounceTimer)
  }, [searchTerm])

  return (
    <div className="fixed inset-0 bg-black/50 z-50 flex items-start justify-center pt-20">
      <div className="bg-white dark:bg-gray-800 w-full max-w-2xl rounded-lg shadow-lg">
        <div className="flex items-center justify-between p-4 border-b dark:border-gray-700">
          <div className="flex-1 mr-4">
            <input
              type="text"
              placeholder="搜索文章... (Esc 关闭)"
              className="w-full px-4 py-2 bg-gray-100 dark:bg-gray-700 rounded-lg focus:outline-none dark:text-white"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              autoFocus
            />
          </div>
          <button
            onClick={onClose}
            className="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 transition-colors"
            aria-label="关闭搜索"
          >
            <svg
              className="w-5 h-5"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
          </button>
        </div>
        
        <div className="max-h-96 overflow-auto">
          {isLoading ? (
            <div className="p-4 text-center text-gray-500 dark:text-gray-400">
              搜索中...
            </div>
          ) : (
            <>
              {results && results.posts?.map((post) => (
                <button
                  key={post.id}
                  className="w-full p-4 text-left hover:bg-gray-100 dark:hover:bg-gray-700 flex flex-col gap-1"
                  onClick={() => {
                    router.push(`/posts/${post.id}`)
                    onClose()
                  }}
                >
                  <h3 className="font-medium dark:text-white">{post.title}</h3>
                  <p className="text-sm text-gray-600 dark:text-gray-300">{post.description}</p>
                  <div className="flex gap-2">
                    {post.tags.map((tag, index) => (
                      <span key={`${post.id}-${tag}-${index}`} className="text-xs text-gray-500 dark:text-gray-400">
                        #{tag}
                      </span>
                    ))}
                  </div>
                </button>
              ))}
              {searchTerm && results && results.posts?.length === 0 && (
                <div className="p-4 text-center text-gray-500 dark:text-gray-400">
                  未找到相关文章，请尝试其他关键词
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  )
} 